package com.CMS.client.ui.view;

import java.util.List;

import com.CMS.client.NameTokens;
import com.CMS.client.PageService;
import com.CMS.client.PageServiceAsync;
import com.CMS.client.datasource.ItemMenuDataSource;
import com.CMS.client.datasource.LanguageDataSource;
import com.CMS.server.domain.Page;
import com.axeiya.gwtckeditor.client.CKConfig;
import com.axeiya.gwtckeditor.client.CKEditor;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.RecordList;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.HeaderControls;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.HeaderControl;
import com.smartgwt.client.widgets.ImgButton;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.CheckboxItem;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.events.ClickEvent;  
import com.smartgwt.client.widgets.events.ClickHandler;

public class EditPageView extends VLayout{
	private static final String DESCRIPTION = "EditPageView";
	private HLayout rollOverCanvas;  
    private ListGridRecord rollOverRecord;	
    //private Canvas canvas = new Canvas("cnvEditor1");
    private Window winModal;
    //private FormPanel editForm = new FormPanel();
    protected SelectItem item;
	protected SelectItem lang;
	protected TextItem pageName;
	protected CheckboxItem visible;
	protected CKEditor editor;
	protected long idPage = 0;
    
	public EditPageView(){
		super();
		
		countryGrid.setShowRollOverCanvas(true);  		  
		  
        countryGrid.setWidth100();  
        countryGrid.setHeight100();  
        countryGrid.invalidateCache();
        countryGrid.setShowAllRecords(true);  
  
        ListGridField idField = new ListGridField("id", "Id", 40);  
        ListGridField nameField = new ListGridField("namePage", "Name Page");  
        ListGridField visibleField = new ListGridField("visiblePage", "Visible");  
        ListGridField languageField = new ListGridField("languagePage", "Language");
        ListGridField itemField = new ListGridField("itemPage", "Item");
        countryGrid.setFields(idField, nameField, visibleField, languageField,itemField);  
        countryGrid.setCanResizeFields(true);  
        countryGrid.setData(getRecords());  

        this.addMember(countryGrid);
        this.draw();
	}
	
	private RecordList getRecords(){
		PageServiceAsync rpc = GWT.create(PageService.class);
		final RecordList records = new RecordList();
		rpc.fetch(new AsyncCallback<List<Page>>() {			
			@Override
			public void onSuccess(List<Page> result) {
				for(int i=0; i<result.size(); i++){
					ListGridRecord r = new ListGridRecord();
					r.setAttribute("id", Long.toString(result.get(i).getId()));
					r.setAttribute("namePage", result.get(i).getName());
					r.setAttribute("visiblePage", result.get(i).getLastVersion().isFlagActiva() == true ? "SI" : "NO" );
					r.setAttribute("languagePage", result.get(i).getLang().getDescription());
					r.setAttribute("itemPage", result.get(i).getItem().getDescription());
					records.add(r);
				}
			}			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub				
			}
		});
		return records;
	}
	
	ClickHandler saveHandler = new ClickHandler() {		
		@Override
		public void onClick(ClickEvent event) {
			PageServiceAsync rpc = GWT.create(PageService.class);
			rpc.update(idPage, pageName.getValueAsString(), "HTML", 
					   new Long(lang.getValue().toString()), 
					   new Long(item.getValue().toString()),
					   editor.getHTML(), visible.getValueAsBoolean(),
					   Cookies.getCookie(NameTokens.USSER_SESSION), new AsyncCallback<Void>() {
						@Override
						public void onFailure(Throwable caught) {
							SC.say(caught.getMessage());							
						}
						@Override
						public void onSuccess(Void result) {
							winModal.hide();
							winModal.destroy();
							winModal = new Window();
							countryGrid.setData(getRecords());
						}
					});
		}
	};
	
	ClickHandler closeHandler = new ClickHandler() {		
		@Override
		public void onClick(ClickEvent event) {
			winModal.hide();
			winModal.destroy();
			winModal = new Window();
		}
	};
	
	final ListGrid countryGrid = new ListGrid() {  
        @Override  
        protected Canvas getRollOverCanvas(Integer rowNum, Integer colNum) {  
            rollOverRecord = this.getRecord(rowNum);  

            HeaderControl save = new HeaderControl(HeaderControl.SAVE, saveHandler);
            HeaderControl close = new HeaderControl(HeaderControl.CLOSE, closeHandler);
            winModal = new Window();              
    		winModal.setTitle("Edit Page");  
    		winModal.setWidth(650);  
    		winModal.setHeight(600);
    		winModal.setHeaderControls(HeaderControls.HEADER_LABEL,save, close);
    		winModal.setIsModal(true);  
    		winModal.setShowModalMask(true);  
    		winModal.centerInPage();
            
            if(rollOverCanvas == null) {  
                rollOverCanvas = new HLayout(3);  
                rollOverCanvas.setSnapTo("TR");  
                rollOverCanvas.setWidth(50);  
                rollOverCanvas.setHeight(22);  

                ImgButton editImg = new ImgButton();  
                editImg.setShowDown(false);  
                editImg.setShowRollOver(false);  
                editImg.setLayoutAlign(Alignment.CENTER);  
                editImg.setSrc("icons/16/letter.png");  
                editImg.setPrompt("Edit Page");  
                editImg.setHeight(16);  
                editImg.setWidth(16);  
                editImg.addClickHandler(new ClickHandler() {  
                    public void onClick(ClickEvent event) {  
                       generarEditor(rollOverRecord.getAttribute("id").toString());
                    }  
                });   
                rollOverCanvas.addMember(editImg);  
            }  
            return rollOverCanvas;  
        }  
    };
	
    private void generarEditor(String id){
    	idPage = new Long(id);
    	item = new SelectItem();
    	item.setTitle("Item de Men&uacute;");
    	item.setOptionDataSource(new ItemMenuDataSource());
    	item.setAccessKey("id");
    	item.setValueField("id");
    	item.setDisplayField("description");
    	lang = new SelectItem();    	
    	lang.setTitle("Idioma");
    	lang.setOptionDataSource(new LanguageDataSource());
    	lang.setAccessKey("id");
    	lang.setValueField("id");
    	lang.setDisplayField("description");
    	pageName = new TextItem();
    	pageName.setTitle("Nombre del Archivo");
    	pageName.setHint("<nobr>.html</nobr>");
    	visible = new CheckboxItem();
    	visible.setTitle("Visible");
    	editor = new CKEditor(getCkConfig());
    	editor.setSize("100%", "100%");
    	
    	final DynamicForm form = new DynamicForm();
    	form.setWidth(400);
    	form.setIsGroup(true);
    	form.setAlign(Alignment.CENTER);
    	form.setPadding(20);
    	form.setFields(item,lang,pageName,visible);    	    	
    	
    	PageServiceAsync rpc = GWT.create(PageService.class);
    	rpc.getPage(new Long(id), new AsyncCallback<Page>() {
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub				
			}
			@Override
			public void onSuccess(Page result) {
				pageName.setValue(removeHtmlExtension(result.getName()));
				visible.setValue(result.getLastVersion().isFlagActiva());
				editor.setHTML(result.getLastVersion().getContent());
				lang.setValue(result.getLang().getId());
				item.setValue(result.getItem().getId());
				winModal.addItem(form);
		    	winModal.addItem(editor);
		    	winModal.show();
			}
		});    	
    }
    
    private String removeHtmlExtension(String cadena){
    	if(cadena.contains(".HTML") || cadena.contains(".Html") || cadena.contains(".html"))
    		return cadena.substring(0, cadena.length() -5);
    	else
    		return cadena;
    }
    
    private CKConfig getCkConfig() {
        CKConfig ckConfig = new CKConfig(CKConfig.PRESET_TOOLBAR.FULL);
        //ckConfig.setWidth("100%");
        //ckConfig.setHeight("100%");
        ckConfig.setBaseFloatZIndex(1000000);
        ckConfig.setUseFormPanel(false);
        ckConfig.setResizeEnabled(true);
        return ckConfig; 
    }
    
	public static class Factory implements ContextAreaFactory{
		private String id;
		 
		public Canvas create(){
			//hay que crear la vista que vamos a llamar
			EditPageView view = new EditPageView();
			id = view.getID();
			return view;
	    }
		 
		public String getID(){
			return id;
		}

		public String getDescription(){
			return DESCRIPTION;
		}
	 }	
}
